import _ from "lodash"
import whiteRoutes from "@/router/routes"
import { getRouteList } from "@/apis/system"
import { decode } from "@/utils/data"

const state = {
	routes: [], // 路由
	updateTime: null, // 路由最后更新时间
}

// 同步设置store.state
const mutations = {
	SET_ROUTES: (state, data) => {
		state.routes = data
	},
	SET_UPDATE_TIME: (state, data) => {
		state.updateTime = data
	},
}

// 异步设置store.state
const actions = {
	updateRoutes({ commit, state }) {
		return new Promise((resolve, reject) => {
			const decodeRoutes = routes => {
				const hander = routes => {
					return routes
						.map(({ path, name, component, redirect, meta, children, seq_no, icon, title, cache }) => {
							return {
								path,
								name,
								component,
								redirect,
								meta: {
									...{
										seq_no,
										icon,
										title,
										cache,
									},
									...(decode(meta) ? decode(meta) : {}),
								},
								children: _.isArray(children) ? hander(children) : [],
							}
						})
						.sort((a, b) => {
							if (!_.isNumber(a.meta.seq_no)) {
								return 1
							} else if (a.meta.seq_no < 0) {
								return -1
							} else {
								return a.meta.seq_no - b.meta.seq_no
							}
						})
				}

				return hander(routes)
			}

			getRouteList()
				.then(response => {
					const { data } = response
					if (_.isArray(response.data)) {
						// 解析meta，排序route
						const routes = decodeRoutes(data)
						routes.splice(routes.length, 0, ...whiteRoutes)
						commit("SET_ROUTES", routes)
						commit("SET_UPDATE_TIME", new Date())
						resolve(routes)
					} else {
						resolve([])
					}
				})
				.catch(error => reject(error))
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
